<template>
   <view class="uv-page" style="background-color: #fff">
      <view class="uv-demo-block">
         <text class="uv-demo-block__title">基础使用</text>
         <view class="uv-demo-block__content">
            <!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
            <uv-form :model="model1" ref="form1">
               <uv-form-item
                  label="姓名"
                  prop="userInfo.name"
                  borderBottom
                  labelWidth="80"
                  ref="item1"
               >
                  <uv-input
                     v-model="model1.userInfo.name"
                     border="none"
                     placeholder="姓名,只能为中文"
                  ></uv-input>
               </uv-form-item>
               <uv-form-item
                  label="性别"
                  prop="userInfo.sex"
                  borderBottom
                  labelWidth="80"
                  @click="showSexSelect"
                  ref="item1"
               >
                  <uv-input
                     v-model="model1.userInfo.sex"
                     disabled
                     disabledColor="#ffffff"
                     placeholder="请选择性别"
                     border="none"
                  ></uv-input>
                  <template v-slot:right>
                     <uv-icon name="arrow-right"></uv-icon>
                  </template>
               </uv-form-item>
               <uv-form-item
                  label="水果"
                  prop="radiovalue1"
                  borderBottom
                  labelWidth="80"
                  ref="item2"
               >
                  <uv-radio-group v-model="model1.radiovalue1" shape="circle">
                     <uv-radio
                        :customStyle="{ marginRight: '16px' }"
                        v-for="(item, index) in radiolist1"
                        :key="index"
                        :label="item.name"
                        :name="item.name"
                     >
                     </uv-radio>
                  </uv-radio-group>
               </uv-form-item>
               <uv-form-item
                  label="兴趣爱好"
                  prop="checkboxValue1"
                  borderBottom
                  labelWidth="80"
                  ref="item3"
               >
                  <uv-checkbox-group v-model="model1.checkboxValue1">
                     <uv-checkbox
                        :customStyle="{ marginRight: '16px' }"
                        v-for="(item, index) in checkboxList1"
                        :key="index"
                        :label="item.name"
                        :name="item.name"
                     >
                     </uv-checkbox>
                  </uv-checkbox-group>
               </uv-form-item>
               <uv-form-item label="简介" prop="intro" borderBottom labelWidth="80" ref="item3">
                  <uv-textarea placeholder="不低于3个字" v-model="model1.intro" count></uv-textarea>
               </uv-form-item>
               <uv-form-item
                  label="住店时间"
                  prop="hotel"
                  borderBottom
                  labelWidth="80"
                  @click="showTimeSelect"
               >
                  <uv-input
                     v-model="model1.hotel"
                     disabled
                     disabledColor="#ffffff"
                     placeholder="请选择住店和离店时间"
                     border="none"
                  ></uv-input>
                  <template v-slot:right>
                     <uv-icon name="arrow-right"></uv-icon>
                  </template>
               </uv-form-item>
               <uv-form-item label="验证码" prop="code" borderBottom labelWidth="80">
                  <uv-input
                     v-model="model1.code"
                     border="none"
                     placeholder="请填写验证码"
                  ></uv-input>
                  <template v-slot:right>
                     <uv-button
                        @tap="getCode"
                        :text="tips"
                        type="success"
                        size="mini"
                        :disabled="disabled1"
                     ></uv-button>
                  </template>
               </uv-form-item>
               <uv-form-item
                  label="生日"
                  prop="userInfo.birthday"
                  borderBottom
                  labelWidth="80"
                  @click="showDateSelect"
                  ref="item1"
               >
                  <uv-input
                     v-model="model1.userInfo.birthday"
                     disabled
                     disabledColor="#ffffff"
                     placeholder="请选择生日"
                     border="none"
                  ></uv-input>
                  <template v-slot:right>
                     <uv-icon name="arrow-right"></uv-icon>
                  </template>
               </uv-form-item>
            </uv-form>

            <uv-button
               type="primary"
               text="提交"
               customStyle="margin-top: 50px"
               @click="submit"
            ></uv-button>
            <uv-button
               type="error"
               text="重置"
               customStyle="margin-top: 10px"
               @click="reset"
            ></uv-button>

            <view>
               <uv-action-sheet
                  ref="sexSelectRef"
                  :round="10"
                  :actions="actions"
                  title="请选择性别"
                  description="如果选择保密会报错"
                  @select="sexSelect"
               >
               </uv-action-sheet>
               <uv-calendar
                  ref="uCalendarRef"
                  mode="range"
                  startText="住店"
                  endText="离店"
                  confirmDisabledText="请选择离店日期"
                  :formatter="formatter"
                  @confirm="calendarConfirm"
                  @close="calendarClose"
               ></uv-calendar>
               <uv-code
                  ref="uCodeRef"
                  :seconds="20"
                  @start="disabled1 = true"
                  @end="disabled1 = false"
                  @change="codeChange"
               ></uv-code>
               <uv-datetime-picker
                  ref="dateSelectRef"
                  v-model="birthday"
                  mode="date"
                  closeOnClickOverlay
                  @confirm="birthdayConfirm"
                  @cancel="birthdayClose"
                  @close="birthdayClose"
               ></uv-datetime-picker>
            </view>
         </view>
      </view>
   </view>
</template>

<script lang="ts" setup>
import { onReady } from '@dcloudio/uni-app';
import { ref } from 'vue';

const item1 = ref<Element>();
const model1 = ref({
   userInfo: {
      name: '楼兰',
      sex: '',
      birthday: '',
   },
   radiovalue1: '苹果',
   checkboxValue1: [],
   intro: '',
   code: '',
   hotel: '',
});

const uCodeRef = ref();
const form1 = ref();
const sexSelectRef = ref();
const uCalendarRef = ref();
const dateSelectRef = ref();

const tips = ref('');
const disabled1 = ref(false);
const birthday = ref(Number(new Date()));

const rules = {
   'userInfo.name': [
      {
         type: 'string',
         required: true,
         message: '请填写姓名',
         trigger: ['blur', 'change'],
      },
      {
         // 此为同步验证，可以直接返回true或者false，如果是异步验证，稍微不同，见下方说明
         validator: (rule: any, value: any, callback: any) => {
            // 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
            return uni.$uv.test.chinese(value);
         },
         message: '姓名必须为中文',
         // 触发器可以同时用blur和change，二者之间用英文逗号隔开
         trigger: ['change', 'blur'],
      },
   ],
   code: {
      type: 'string',
      required: true,
      len: 4,
      message: '请填写4位验证码',
      trigger: ['blur'],
   },
   'userInfo.sex': {
      type: 'string',
      max: 1,
      required: true,
      message: '请选择男或女',
      trigger: ['blur', 'change'],
   },
   radiovalue1: {
      type: 'string',
      min: 1,
      max: 2,
      message: '橙子有毒',
      trigger: ['change'],
   },
   checkboxValue1: {
      type: 'array',
      min: 2,
      required: true,
      message: '不能太宅，至少选两项',
      trigger: ['change'],
   },
   intro: {
      type: 'string',
      min: 3,
      required: true,
      message: '不低于3个字',
      trigger: ['change'],
   },
   hotel: {
      type: 'string',
      min: 2,
      required: true,
      message: '请选择住店时间',
      trigger: ['change'],
   },
   'userInfo.birthday': {
      type: 'string',
      required: true,
      message: '请选择生日',
      trigger: ['change'],
   },
};
const actions = ref([
   {
      name: '男',
   },
   {
      name: '女',
   },
   {
      name: '保密',
   },
]);
const radiolist1 = ref([
   {
      name: '苹果',
      disabled: false,
   },
   {
      name: '香蕉',
      disabled: false,
   },
   {
      name: '毒橙子',
      disabled: false,
   },
]);
const checkboxList1 = ref([
   {
      name: '羽毛球',
      disabled: false,
   },
   {
      name: '跑步',
      disabled: false,
   },
   {
      name: '爬山',
      disabled: false,
   },
]);

const showTimeSelect = () => {
   uCalendarRef.value.open();
};
const showSexSelect = () => {
   sexSelectRef.value.open();
   uni.hideKeyboard();
};
const codeChange = (text: string) => {
   tips.value = text;
};
const getCode = () => {
   if (uCodeRef.value.canGetCode) {
      // 模拟向后端请求验证码
      uni.showLoading({
         title: '正在获取验证码',
      });
      setTimeout(() => {
         uni.hideLoading();
         // 这里此提示会被this.start()方法中的提示覆盖
         uni.$uv.toast('验证码已发送');
         // 通知验证码组件内部开始倒计时
         uCodeRef.value.start();
      }, 2000);
   } else {
      uni.$uv.toast('倒计时结束后再发送');
   }
};

const showDateSelect = () => {
   dateSelectRef.value.open();
};

const submit = () => {
   form1.value
      .validate()
      .then((res: any) => {
         uni.$uv.toast('校验通过');
      })
      .catch((errors: any) => {
         uni.$uv.toast('校验失败');
         console.log(errors);
      });
};

const reset = () => {
   form1.value.resetFields();
};

const sexSelect = (e: any) => {
   model1.value.userInfo.sex = e.name;
   form1.value.validateField('userInfo.sex');
};
const formatter = (day: any) => {
   // 日历格式化函数 - 根据官方示例
   const d = new Date();
   const month = d.getMonth() + 1;
   const date = d.getDate();

   // 可以在这里添加自定义的日期标记
   if (day.month == month && day.day == date + 3) {
      day.bottomInfo = '优惠';
      day.dot = true;
   }
   return day;
};

const calendarConfirm = (selectedDates: string[]) => {
   // 住店时间确认 - selectedDates 是字符串数组
   if (selectedDates.length > 1) {
      // 范围选择模式
      model1.value.hotel = `${selectedDates[0]} 至 ${selectedDates[selectedDates.length - 1]}`;
   } else if (selectedDates.length === 1) {
      // 单日选择模式
      model1.value.hotel = selectedDates[0];
   }
   // 触发表单验证
   form1.value.validateField('hotel');
};

const calendarClose = () => {
   // 日历关闭
};

const birthdayConfirm = (e: any) => {
   // 生日确认 - datetime-picker 的确认事件
   const date = uni.$uv.timeFormat(e.value, 'yyyy-mm-dd');
   model1.value.userInfo.birthday = date;
   // 触发表单验证
   form1.value.validateField('userInfo.birthday');
};

const birthdayClose = () => {
   // 生日选择器关闭
};

onReady(() => {
   // 延迟设置规则，确保组件完全初始化
   setTimeout(() => {
      if (form1.value) {
         form1.value.setRules(rules);
      }
   }, 100);
});
</script>

<style lang="scss" scoped></style>
